<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">产品数据下发新建</p>
    </div>
    <div class="view-container">
      <el-row class="status-title">
        <el-col class="mr20 width100">
          <el-button
            class="btn-success width100"
            type="primary"
            @click="submitForm()"
          >确定执行</el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="form" label-width="140px" class="mt30">
        <el-row>
          <el-col :span="8">
            <el-form-item label="编码:">
              <el-input placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="下发类型:" prop="dataType">
              <el-select v-model="form.dataType" style="width:100%;" placeholder="请选择">
                <el-option label="产品下发" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="选择公司组织:">
              <el-select v-model="organizationDepts" style="width:100%;" multiple placeholder="请选择" value-key="id" @change="getSysDepts">
                <el-option
                  v-for="item in organizationList"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择产品:">
              <el-button
                class="btn-default width100"
                type="primary"
                @click="onClickLayer"
              >选择产品</el-button>
              <div v-for="(item, index) in ids" :key="index">
                {{ item.specificationCode + '-' + item.specificationName }}
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(item)"
                ></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 产品弹出对话框 -->
    <el-dialog title="产品" :visible.sync="open" width="90%" top="50px" append-to-body center>
      <el-row class="mb8">
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
          >展开/折叠</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-table v-if="refreshTable" v-loading="loading" :data="productList" row-key="id"
            :default-expand-all="isExpandAll"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="sortName" label="分类名称" width="150">
              <template slot-scope="scope">
                <span @click="handleItem(scope.row)" style="cursor:pointer">{{ scope.row.sortName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortCode" label="分类编码" align="center"></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="1">
          <div class="line-layer"></div>
        </el-col>
        <el-col :span="17">
          <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
            <el-form-item prop="searchValue">
              <el-input
                v-model="queryParams.searchValue"
                placeholder="名称或者编码模糊查询"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="searchProductList" ref="materialTable" @selection-change="handleSelectionChange" :row-key="getRowKeys">
            <el-table-column type="selection" width="35" align="center" :reserve-selection="true" />
            <el-table-column label="序号" type="index" align="center" width="50">
              <template slot-scope="scope">
                <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column label="SKU编码" align="center" prop="specificationCode" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="SKU名称" align="center" prop="specificationName" :show-overflow-tooltip="true" width="180" />
            <el-table-column label="规格" align="center" :show-overflow-tooltip="true" width="150">
              <template slot-scope="scope">
                {{ scope.row.value1 == null ? '' : scope.row.value1 + scope.row.value2 }}
              </template>
            </el-table-column>
            <el-table-column label="助记码" align="center" prop="mnemonicCode"  :show-overflow-tooltip="true" width="150" />
            <el-table-column label="产品分类" align="center" prop="productClassification" :show-overflow-tooltip="true" width="100" />
            <el-table-column label="有效天数" align="center" prop="validDate" :show-overflow-tooltip="true" width="100" />
            <el-table-column label="品牌" align="center" prop="brandId" :show-overflow-tooltip="true" width="100" />
            <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true" />
            <el-table-column label="是否启用扫码" align="center" prop="isSerial" width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.isSerial == '0'" style="color:#13C2C2">是</div>
                <div v-if="scope.row.isSerial == '1'" style="color:#52C41A">否</div>
                <div v-else></div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="批次与序列号" align="center" prop="serialNumber" width="100">
              <template slot-scope="scope">
                <div v-if="scope.row.serialNumber == '0'" style="color:#13C2C2">启用</div>
                <div v-if="scope.row.serialNumber == '1'" style="color:#52C41A">禁用</div>
              </template>
            </el-table-column> -->
            <el-table-column label="审核状态" align="center" prop="approvalStatus">
              <template slot-scope="scope">
                <div v-if="scope.row.approvalStatus == 0" style="color:#13C2C2"></div>
                <div v-if="scope.row.approvalStatus == 1" style="color:#13C2C2">待审核</div>
                <div v-if="scope.row.approvalStatus == 2" style="color:#52C41A">已通过</div>
                <div v-if="scope.row.approvalStatus == 3" style="color:#fd562c">拒绝</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="productStatus">
              <template slot-scope="scope">
                <div v-if="scope.row.productStatus == 0" style="color:#13C2C2">禁用</div>
                <div v-if="scope.row.productStatus == 1" style="color:#52C41A">正常</div>
              </template>
            </el-table-column>
            <template v-for="(a, index) in organizationList">
              <el-table-column :label="a.orgName" prop="deptList" align="center" :key="index" width="200">
                <template slot-scope="scope">
                  <template v-for="item in scope.row.deptList">
                    <template v-if="item">
                      <template v-if="item.deptId == a.deptId">
                        <el-checkbox :value="true" :key="item.deptId" disabled class="on-checked" ></el-checkbox>
                      </template>
                    </template>
                  </template>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="handleItem()"
          />
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addProductDataReleased } from "@/api/system/basedata/dataReleased/dataReleased"
import { organizationList } from "@/api/system/organization/organization"
import { listProductList, searchSku } from "@/api/system/basedata/productlist/productlist"
import { listBrand } from "@/api/system/basedata/brand/brand"

export default {
  name: "add",
  data(){
    return {
      form: {
        dataIds: [],
        dataType: '4', // 下发类型
        sysDepts: [], // 选中组织数据
      },
      organizationDepts: [],
      organizationList: [], // 公司组织列表
      open: false,
      loading: true,
      productList: [], // 产品分类列表
      isExpandAll: true,
      refreshTable: true,
      searchProductList: [], // 产品列表
      // 查询参数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sortId: '',
        productStatus : 1,
        approvalStatus: 2,
        searchValue: undefined
      },
      ids: [],
    }
  },
  created() {
    this.getOrganizationList()
    this.getProductList()
  },
  methods: {
    // 获取公司组织列表
    getOrganizationList() {
        organizationList({status: 0}).then(res => {
          this.organizationList = res.rows
        })
    },
    // 选中数据结构转换
    getSysDepts(e){
      let arr = []
      e.forEach(i => {
        let obj = {
          deptId: i.deptId,
          deptName: i.orgName
        }
        arr.push(obj)
      })
      this.form.sysDepts = arr
    },
    // 弹窗显示
    onClickLayer(){
      this.open = true
      this.handleItem()
    },
    // 获取产品分类列表
    getProductList() {
      this.loading = true
      listProductList().then(res => {
        this.productList = this.handleTree(res.rows, "id")
        this.loading = false
      })
    },
    // 转换产品分类数据结构 
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.sortName,
        children: node.children
      }
    },
    // 展开/折叠
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    // 根据分类查看产品
    handleItem(item){
      if(item !== undefined){
        this.queryParams.sortId = item.id
      }
      searchSku(this.addDateRange(this.queryParams)).then(res => {
        this.searchProductList = res.rows
        this.total = res.total
        this.getProductClass()
        this.getBrand()
      })
    },
    // 获取产品分类
    getProductClass(){
      listProductList().then(res => {
        this.searchProductList.forEach(item => {
          let arr = res.rows.find(e =>{
            return e.id == item.productClassification
          })
          if(arr != undefined){
            item.productClassification = arr.sortName
          }
        })
      })
    },
    // 获取品牌
    getBrand(){
      listBrand(this.addDateRange({status: 0})).then(res => {
        this.searchProductList.forEach(item => {
          let arr = res.rows.find(e => {
            return e.id == item.brandId
          })
          if(arr != undefined){
            item.brandId = arr.brandName
          }
        })
      })
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.handleItem()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 翻页不清空
    getRowKeys(row){
      return row.id
    },
    // 选中产品
    handleSelectionChange(row){
      this.ids = row.map(item => item)
      this.form.dataIds = this.ids.map(id => id.id)
    },
    // 删除产品
    handleDelete(item){
      let index = this.ids.findIndex(i => {
        return i.id == item.id
      })
      // this.ids.splice(index, 1)
      this.form.dataIds.splice(index, 1)
      // 清除当前选中产品
      // this.ids.forEach(i => {
        // this.$nextTick(() => {
          this.searchProductList.find(y => {
            if(item.id == y.id){
              this.$refs.materialTable.toggleRowSelection(y, false)
            }
          })
        // })
      // })
    },
    // 提交数据
    submitForm() {
      if(this.form.sysDepts.length == 0){
        this.$modal.msgError('请选择公司组织！')
      }else if(this.form.dataIds.length == 0){
        this.$modal.msgError('请选择产品！')
      }else{
        this.$modal.loading("正在提交")
        addProductDataReleased(this.form).then(res => {
          this.$tab.closeOpenPage({ path: "/basedata/product/dataReleased" })
          this.$modal.msgSuccess("下发成功!")
          this.$modal.closeLoading()
        })
      }
    }
  }
}
</script>